package com.gskj.gulimall.seckill.controller;

import club.gskj.common.utils.R;
import com.gskj.gulimall.seckill.service.SeckillService;
import com.gskj.gulimall.seckill.to.SeckillSkuRedisTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/***
 *  商品秒杀控制器
 */
@Controller
public class SeckillController {

    @Autowired
    private SeckillService seckillService;

    /***
     *  返回当前时间可以参与秒杀的商品列表信息
     * @return
     */
    @GetMapping("/currentSeckillSkus")
    @ResponseBody
    public R getCurrentSeckillSkus() {
        List<SeckillSkuRedisTO> list = seckillService.getCurrentSeckillSkus();

        return R.ok().setData(list);
    }

    /**
     * 根据skuid 获取当前商品的秒杀信息
     */
    @GetMapping("/sku/seckill/{skuId}")
    @ResponseBody
    public R getSkuSeckillInfo(@PathVariable("skuId") Long skuId) {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        SeckillSkuRedisTO to = seckillService.getSkuSeckillInfo(skuId);
        return R.ok().setData(to);
    }

    /***
     * TODO 开始商品秒杀功能！
     * @param killId 缓存的商品keu值
     * @param code 商品验证码
     */
    @GetMapping("/kill")
    public String secKill(@RequestParam("killId") String killId,
                          @RequestParam("code") String code,
                          @RequestParam("num") Integer num, Model model) {
        // 执行商品秒杀，返回此次秒杀的订单号
        String orderSn = seckillService.kill(killId, code, num);

        model.addAttribute("orderSn", orderSn);
        return "success";
    }

}
